package com.comtrade.activities;


import java.util.List;
import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.comtrade.ilserver.tasks.BeaconServer;
import com.comtrade.ilserver.tasks.GetBeaconTask;
import com.comtrade.ilserver.tasks.GetSpaceTask;
import com.comtrade.ilserver.tasks.ImageDownload;
import com.comtrade.ilserver.tasks.Space;
import com.comtrade.ilserver.tasks.User;
import com.comtrade.sharedpreferences.DomesticSharedPreferences;
import com.estimote.sdk.Beacon;
import com.estimote.sdk.BeaconManager;
import com.estimote.sdk.BeaconManager.RangingListener;
import com.estimote.sdk.Region;
import com.example.beaconapk.R;

public class GuideActivity extends Activity {
	private static final String TAG = GuideActivity.class.getSimpleName();
	
	private static final int REQUEST_ENABLE_BT = 1234;
	private static final Region ALL_ESTIMOTE_BEACONS_REGION = new Region("rid",
			null, null, null);

	private BeaconManager beaconManager;
	private List<Beacon> Beaconi;
	private DomesticSharedPreferences sharedPreferences;
	private boolean indikator = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_guide);
		sharedPreferences = new DomesticSharedPreferences();
		
		beaconManager=new BeaconManager(getBaseContext());
		ProgressBar pbar=(ProgressBar) findViewById(R.id.progressBar);
        pbar.incrementProgressBy(10);
		beaconManager.setRangingListener(new RangingListener() {
    		@Override
    		public void onBeaconsDiscovered(Region arg0, List<Beacon> arg1) {
    			// TODO Auto-generated method stub
    			Beaconi=arg1;
    			runOnUiThread(new Runnable() {
    				@Override
    				public void run() {
    					
    					int br=0;
    					for (Beacon beacon : Beaconi) {
    						br++;
    					}
    					Log.d("Tag I","Izbrojao je "+br+" beacona.");
    					if (br!=0 && !indikator){
    						String mac=Beaconi.get(0).getMacAddress().toString();
    						indikator=true;
    						// vuce iz shared
    						String username=sharedPreferences.getPreferences(getApplicationContext(), "USERNAME"); 
    						String password=sharedPreferences.getPreferences(getApplicationContext(), "PASSWORD"); 
    						String ILServer= sharedPreferences.getPreferences(getApplicationContext(), "URL");
    						GetBeaconTask task = new GetBeaconTask();
    						// naci username i pass
    						task.setMacAddress(mac);
    						task.setUsername(username);
    						task.setPassword(password);
    						task.execute(ILServer+"/rest/getBeacon");
    						Log.d("Beacon",ILServer+" JEA");
    						try {
								String jsonBeacon=task.get();
								Log.d("BEACON MAC", "123 "+jsonBeacon);
								if (jsonBeacon==null)
									Log.d("GET","Ne radi task.get()");
								else
									Log.d("GET","Radi task.get() "+jsonBeacon+"KAMEN ");
								BeaconServer bs=BeaconServer.fromJSON(jsonBeacon);
								Log.d("GET", bs.get_uuid()+" RADI");
								GetSpaceTask task2= new GetSpaceTask();
								task2.setPassword(password);
								task2.setUsername(username);
								task2.setSpaceId(bs.getSpaceId());
								Log.d("SpaceID",ILServer+"/rest/getSpace");
								task2.execute(ILServer+"/rest/getSpace");
								String aboutSpace=task2.get();
								Log.d("JSON",aboutSpace);
								Space sc = Space.fromJSON(aboutSpace);
								Log.d("GUIDE", aboutSpace);
								String urlSlike=sc.getMapAddress();
								ImageDownload Slika=new ImageDownload();
								Slika.setUrl(ILServer+"/"+urlSlike);
								Slika.execute();
								byte[] nizbitova=Slika.get();
								Intent in= new Intent(GuideActivity.this,DeviceActivity.class);
								in.putExtra("image", nizbitova);
								in.putExtra("space", sc);
								
							//	User korisnik =(User )getIntent().getExtras().get("USER");								
							//	in.putExtra("USER", korisnik);
								Toast t = Toast.makeText(getApplicationContext(), sc.getTitle(), Toast.LENGTH_SHORT);
								t.show();
								startActivity(in);
								
							}catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (ExecutionException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
    					}
    				}
    			});

    		}
    	});
	}

	@Override
	protected void onStart() {
		super.onStart();

		// iBeacons
		// Check if device supports Bluetooth Low Energy.
		if (!beaconManager.hasBluetooth()) {
			Toast.makeText(this, "Device does not have Bluetooth Low Energy",
					Toast.LENGTH_LONG).show();
			return;
		}

		// If Bluetooth is not enabled, let user enable it.
		if (!beaconManager.isBluetoothEnabled()) {
			Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
		} else {
			connectToService();
		}

	}

	private void connectToService() {
		beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
			@Override
			public void onServiceReady() {
				try {
					beaconManager.startRanging(ALL_ESTIMOTE_BEACONS_REGION);
				} catch (RemoteException e) {
					Toast.makeText(
							GuideActivity.this,
							"Cannot start ranging, something terrible happened",
							Toast.LENGTH_LONG).show();
					Log.e(TAG, "Cannot start ranging", e);
				}
			}
		});
	}

	@Override
	protected void onStop() {
		//Ovo mozda treba u onDestroy() :D
		/*try {
			beaconManager.stopRanging(ALL_ESTIMOTE_BEACONS_REGION);
			beaconManager.disconnect();
		} catch (RemoteException e) {
			//e.printStackTrace();
		}*/
		super.onStop();
	}
	
	@Override
	protected void onDestroy() {
		
		super.onDestroy();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_ENABLE_BT) {
			if (resultCode == Activity.RESULT_OK) {
				connectToService();
			} else {
				Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_LONG)
				.show();
				getActionBar().setSubtitle("Bluetooth not enabled");
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}


}
